//
//  ViewController.swift
//  yiplayer
//
//  Created by cgw on 2024/5/7.
//

import UIKit
import FileBrowser

class ViewController: UIViewController {
    
    let tf = UITextField()
    let tv = UITextView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        self.downloadFile()
        //self.addFaGuangView()
        
        return;
        
    
        let wordTf = tf.font(14).color(Color3)
        wordTf.bg(ColorF3F6FB).margin(0,-15).pin(.h(50))
        wordTf.placeholder = "歌名"
        wordTf.clearButtonMode = .whileEditing
        
        let noteView = tv.font(14).color(Color3)
        noteView.bg(ColorF3F6FB).margin(-20,-15)
        
        let sureBtn = Button.font(Font14).color(ColorF).bg(ColorMain)
        sureBtn.str("查询").pin(.wh(110, 50))
        sureBtn.onTap {
            self.handleBtn()
        }
        
        let fileBtn = Button.font(Font14).color(ColorF).bg(ColorMain)
        fileBtn.str("浏览").pin(.wh(110, 50))
        fileBtn.onTap {
            self.handleFileBtn()
        }
        
        VStack(60, wordTf, noteView, sureBtn,20,fileBtn,50).embedIn(self.view).align(.center)
        
        wordTf.makeCons { make in
            make.left.equal(15)
            make.right.equal(-15)
        }
    }
    
    func addFaGuangView() {
        let v = UIView(frame: .init(x: 100, y: 200, width: 200, height: 200))
        v.backgroundColor = .red
        
        v.shadow(0.5,10,0,0,"blue")
        v.addTo(self.view)
        
        let ani = CABasicAnimation(keyPath: "shadowOpacity")
        ani.fromValue = 0.0
        ani.toValue = 0.8
        ani.autoreverses = true
        ani.duration = 1.0
        ani.repeatCount = HUGE
        v.layer.add(ani, forKey: "shadowOpacity")
    }
    
    func handleFileBtn() {
//        self.playVideo()
        //let url = BLPath.documentPath()?.toFileUrl()
//        let fn = "一叶-今天(婚礼版 抖音热歌).mp3"
        
        return;
                
        let url = YiFilePath.share.songDir.toFileUrl()
        //PathManager.share.getDocumentsDirectory()
        let browder = FileBrowser.init(initialPath: url)
        self.present(browder, animated: true)
    }
    
    func handleBtn() {
        
        let od = self.tf.text ?? ""
        let str = od.replaceInvalidCharacters()
        
        print("old: "+od)
        print("new: "+str)
        
        let c = ListCtrl()
        c.key = str
        self.present(c, animated: true)
        
        return;
        
        // 2019709443
//        YIHttp.neteaseMp3Url(caller: self, songId: "554191989") { data, err in
//            print("\n\n\n==========song url==============")
//            print(data)
//        }
//        YIHttp.downloadNeteaseLyric(caller: self, songId: "554191989") { data, err in
//            print("------------Lyric-----------\n\n\n\n")
//            print(data)
//        }
        
        
//        return
        
        let para = ["ids": [2014882300], "br": 32000] as [String : Any]
        let ret = NeteaseApi.encodeNeteaseData(para)
        print("结果")
        print(ret)
        let ret1 = NeteaseApi.encryptedRequest(para: para)
        print("结果2")
        print(ret1)
        
        YIHttp.neteaseSearch(caller: self, keyword: "今天 刘德华") { data, err in
            
        }
    }
    
    let ctrl = BLVideoPlayer()
    func playVideo() {
        
        let fn = "1.mp4"
        if let ul = YiFilePath.share.songDir.appendPath(pathname: fn).toFileUrl() {
            
            
            ctrl.modalPresentationStyle = .overCurrentContext
            ctrl.controlView.titleL.text = "一万个理由.mp4"
            self.present(ctrl, animated: true) {
                self.ctrl.play(withURL: ul, videoTitle: "一万个理由.mp4")
            }
            
        }else{
            return
        }
    }
    
    func downloadFile() {
        let mp4Url = "https://vd3.bdstatic.com/mda-phv1zugg2n3c8n4n/720p/h264/1693358819109409657/mda-phv1zugg2n3c8n4n.mp4?v_from_s=hkapp-haokan-hbe&auth_key=1693663538-0-0-533e7ed71380a893120cc0762bf2b3a0&bcevod_channel=searchbox_feed&cr=2&cd=0&pd=1&pt=3&logid=0338572677&vid=4140107770816422827&klogid=0338572677&abtest=112751_3"
        guard let ul = URL.init(string: mp4Url) else { return }
        
        
        let td = YiFilePath.share.songDir
        
        YIHttp.download(url: mp4Url, toDir: td, fileName: "1.mp4") { pro in
            
        } complete: { fp, err in
            if err == nil {
                print("下载完成")
                print(fp)
            }else {
                print("下载失败")
            }
        }
    }
}



/* 设置页面
 
 设置

 密码         开关，打开进入密码页面
 解码器       进入单选列表
  
 文本编码      进入单选列表
 允许备份      开关
 开启手势      开关
 显示菜单按钮   开关
 菜单项        进入多选列表

 Open Source --> 进入列表

 关于         弹出一个简单的页面
 
 自动续播 （下一集）
 停止播放当前视频
 字幕选择（）
 
 
 */


class HomeListCtrl: UITableViewController {
    
    var datas: [String]?
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.datas = ["none", "App" , "文件浏览" , "网易测试", "播放smb视频", "BLVideoPlayer"]
        
        self.tableView.register(ListCell.self, forCellReuseIdentifier: "reuseIdentifier")
        self.tableView.rowHeight = 50.0
        self.view.backgroundColor = .white
        
        self.tableView.reloadData()
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return datas?.count ?? 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! ListCell

        // Configure the cell...
        let m = self.model(datas, indexPath) as? String
        cell.nameL.text = m

        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        
        let i = indexPath.row
        
        if i == 0 {
            
            let ctrl = YiBgCtrl()
            ctrl.modalPresentationStyle = .overCurrentContext
            self.present(ctrl, animated: true)
        }
        
        if i == 1 {
            //app
            let ctrl = YiHomeCtrl()
            ctrl.modalPresentationStyle = .overCurrentContext
            self.present(ctrl, animated: true)
        }
        else if i == 2 {
            //文件浏览
            let url = YiFilePath.share.songDir.toFileUrl()
            //PathManager.share.getDocumentsDirectory()
            let browder = FileBrowser.init(initialPath: url)
            self.present(browder, animated: true)
        }else if i == 3 {
            //网易测试
            let ctrl = ViewController()
            ctrl.modalPresentationStyle = .overCurrentContext
            self.present(ctrl, animated: true)
        }else if i == 4 {
            //播放smb中视频
            self.present(VLCMediaCtrl(), animated: true)
        }else if i == 5 {
            //BLVideoPlayer
            self.present(BLVideoPlayer(), animated: true)
        }
    }
}
